package cn.phub.basic.interceptor;

import cn.phub.basic.annotation.PreAuthorize;
import cn.phub.basic.jwt.JwtUtils;
import cn.phub.basic.jwt.Payload;
import cn.phub.basic.jwt.RsaUtils;
import cn.phub.basic.jwt.UserInfo;
import cn.phub.system.mapper.PermissionMapper;
import cn.phub.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/**
 * 自定义登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String jwtRsaPublic;//公钥的文件名字

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断有没有携带token
        String token = request.getHeader("U-TOKEN");//变成了jwt串
        //报错并让前端定位到登录页 向response中写AJaxResult
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        if(!StringUtils.isEmpty(token)){
            //根据token--解密token得到登录人相关的所有信息
            PublicKey publicKey = RsaUtils
                .getPublicKey((FileCopyUtils
                    .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPublic))));
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            Logininfo loginTmp = userInfo.getUser();
            if(loginTmp != null){
                //查看是否是员工还是用户
                if(loginTmp.getType() == 0){
                    //如果是员工 需要单独校验当前登录的员工，是否有权限访问当前资源
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
                    //当前这个方法打了注解，那么就需要校验权限，拥有权限才能访问
                    if(preAuthorize != null){
                        //获取当前请求的资源
                        String permisionSn = preAuthorize.value();
                        //查询出当前登录人所拥有的资源权限
                        List<String> ownPers = userInfo.getPermissions();
                        //比对当前访问的资源是否包含在登录人所拥有的权限中
                        if(!ownPers.contains(permisionSn)){
                            //如果不在 提示没有权限访问，直接返回 {"success":false,"message":"noPermission"}
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                        //如果在就直接放行
                    }
                }
                //如果是用户，直接放行不用校验权限
                //放行并刷新过期时间
                //这里要刷新JWT的过期时间，我目前做不到--直接放弃
//                redisTemplate.opsForValue().set(token,loginTmp,30, TimeUnit.MINUTES);
                return true;//放行
            }
        }
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        //阻止放行
        return false;
    }

}
